<template>
  <div>
    <!-- 渲染角色列表 -->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <el-row class="footer" type="flex" justify="center">
      <!-- 复选框组 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="addRole">确定</el-button>
        <el-button size="small" @click="cancleDialog">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getRoles } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    parentId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      roleIds: [], // 存放已选的角色id
      roleList: [] // 所有角色列表
    }
  },
  created() {
    // 调用获取角色列表
    this.getRoles()
    // 调用获取角色详情方法
    this.getUserDetailById()
  },
  methods: {
    // 取消分配角色
    cancleDialog() {
      this.$emit('close')
    },
    // 获取角色详情
    async getUserDetailById() {
      const res = await getUserDetailById(this.parentId)
      this.roleIds = res.data.roleIds
    },
    // 获取所有角色列表
    async getRoles() {
      const res = await getRoles()
      this.roleList = res.data.rows
    },
    // 点击确定,分配角色
    async addRole() {
      const res = await assignRoles({ id: this.parentId, roleIds: this.roleIds })
      this.$message.success(res.message)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 20px;
}

</style>
